package com.lab.app;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.SuperFragmentUtil;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cuitrip.app.MainApplication;
import com.cuitrip.app.util.FontManager;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.service.BuildConfig;
import com.cuitrip.util.DialogUtil;
import com.lab.component.common.BaseDialogFragment;
import com.lab.component.common.IUIController;
import com.lab.logtrack.AppLog;
import com.squareup.leakcanary.RefWatcher;

import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;

import cn.pedant.SweetAlert.SweetAlertDialog;
import rx.Subscriber;

public class BaseFragment extends Fragment implements IUIController {
    private static final int REQUEST_LOGIN = 10001;

    private WeakReference<? extends BaseActivity> mWeakHostActivity;

    private SweetAlertDialog mLoadingDialog;
    private SweetAlertDialog mNoCancelDialog;

    protected Set<Subscriber> subscriberSet = new HashSet<>();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mWeakHostActivity = new WeakReference<BaseActivity>((BaseActivity) activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (null != mWeakHostActivity) {
            mWeakHostActivity.clear();
            mWeakHostActivity = null;
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return null;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int layoutResId) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(layoutResId, container, false);
        FontManager.changeRootViewFonts(rootView);
        return rootView;
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, View rootView) {
        super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    /**
     * 获取宿主Activity
     *
     * @return
     */
    public final BaseActivity getHostActivity() {
        if (null != mWeakHostActivity)
            return mWeakHostActivity.get();
        return null;
    }

    public void showActionBar(String title) {
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            ActionBar actionbar = ((BaseActivity) getActivity()).getSupportActionBar();
            if (actionbar != null) {
                actionbar.setTitle(title);
                actionbar.show();
            }
        }
    }

    public void hideActionBar() {
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            ActionBar actionbar = ((BaseActivity) getActivity()).getSupportActionBar();
            if (actionbar != null) {
                actionbar.hide();
            }
        }
    }

    public ActionBar getActionBar() {
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            return ((BaseActivity) getActivity()).getSupportActionBar();
        } else {
            return null;
        }
    }

    protected void showLoading() {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = DialogUtil.createSweetLoadingProgressDialog(activity, true);
        }
        mLoadingDialog.show();
    }

    protected void hideLoading() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    protected void showNoCancelDialog() {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        if (mNoCancelDialog == null) {
            mNoCancelDialog = DialogUtil.createSweetLoadingProgressDialog(activity, false);
        }
        mNoCancelDialog.show();
    }

    protected void hideNoCancelDialog() {
        if (mNoCancelDialog != null) {
            mNoCancelDialog.dismiss();
        }
    }

    public void onDestroy() {
        super.onDestroy();
        if (mNoCancelDialog != null && mNoCancelDialog.isShowing()) {
            mNoCancelDialog.dismiss();
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (BuildConfig.DEBUG){
            RefWatcher refWatcher = MainApplication.getInstance().getRefWatcher();
            if (refWatcher != null){
                refWatcher.watch(this);
            }
        }
    }

    protected void onNetwokError(int nameRes, int drawableRes, int layout) {

    }

    protected void onEmpyData(int nameRes, int drawableRes, int layout) {

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_LOGIN) {
            if (resultCode == Activity.RESULT_OK && LoginInstance.isLogin()) {
                onLoginSuccess();
                return;
            } else {
                onLoginFailed();
            }
        }
    }

    protected void onLoginSuccess() {

    }

    protected void onLoginFailed() {

    }

    @Override
    public final FragmentManager getOptimizedFragmentManager() {
        return this.getChildFragmentManager();
    }

    @Override
    public void showDialogFragment(BaseDialogFragment dialog) {
        if (null != dialog && isAdded()) {
            try {
                getHostActivity().showDialogFragment(dialog);
            } catch (Exception e) {
                AppLog.w(e.getMessage());
            }
        }
    }

    @Override
    public void hideDialogFragment(BaseDialogFragment dialog) {
        if (null != dialog) {
            try {
                getHostActivity().hideDialogFragment(dialog);
            } catch (Exception e) {
                AppLog.w(e.getMessage());
            }
        }
    }

    public Subscriber addSubscriber(Subscriber subscriber){
        subscriberSet.add(subscriber);
        return subscriber;
    }


    private void releaseSubscribers(){
        for (Subscriber subscriber : subscriberSet){
            if (!subscriber.isUnsubscribed()){
                subscriber.unsubscribe();
            }
        }
    }

    /**
     * 返回操作，处理嵌套
     *
     * @return
     */
    public boolean onBackPressed(boolean fromKey) {
        if (fromKey) {
            return directBackPressed();
        } else {
            return onBackPressed();
        }
    }

    /**
     * 返回操作，处理嵌套
     *
     * @return
     */
    public boolean onBackPressed() {
        FragmentManager childFragmentManager = getChildFragmentManager();
        if (SuperFragmentUtil.tryToPopUpFragment(childFragmentManager)) {
            return true;
        } else {
            return directBackPressed();
        }
    }

    public boolean directBackPressed() {
        FragmentManager fragmentManager = getFragmentManager();
        return SuperFragmentUtil.tryToDirectPopUpFragment(fragmentManager);
    }


}
